package com.fyb.basic.juc.masterWork;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 工作线程
 */
public class Worker<R> {
    /**
     * 基于数组的阻塞队列
     */
    private final ArrayBlockingQueue<Task<R>> arrayBlockingQueue = new ArrayBlockingQueue<>(1024);

    private static final AtomicInteger WORKER_ID_GENERATOR = new AtomicInteger();

    private final int workerId;

    private final Thread workerThread;

    public Worker() {
        this.workerId = WORKER_ID_GENERATOR.getAndIncrement();
        workerThread = new Thread(this::execute);
        workerThread.start();
    }

    /**
     * worker 调用execut 方法
     */
    private void execute() {
        while (true) {
            Task<R> task = null;
            try {
                task = arrayBlockingQueue.take();
                task.setWorkerId(workerId);
                task.execute();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }

    public void submit(Task<R> task) {
        arrayBlockingQueue.offer(task);
    }
}
